<?php

App::uses('AdminController', 'Controller');

class AdminSlideshowController extends AdminController {
    
    public $uses = array('Slideshow');
    
    public function index() {
        $this->set('slideshow', $this->Slideshow->find('all'));
    }
    
    public function create() {
        $this->set('data', $this->Slideshow->create());
        $this->render('form');
    }
    
    public function edit($id) {
        $this->set('data', $this->Slideshow->findById($id));
        $this->render('form');
    }
    
    public function save() {
        $data = $this->data;
        if (! empty($data)) {
            $this->Slideshow->create($data);
            
            if (! $this->Slideshow->validates()) {
                $this->set('data', $data);
                $this->setFlash('Uneti podacu nisu validni.');
                return $this->render('form');
            }
            
            $toupload = array();
            if (! $data['Slideshow']['image_file']['error']) {
                $toupload = $data['Slideshow']['image_file'];
                $data['Slideshow']['image'] = $toupload['name'];
            }
            
            if (! $this->Slideshow->save($data)) {
                $this->set('data', $data);
                $this->setFlash('Grešaka pri čuvanju podataka.');
                return $this->render('form');
            }
            
            if (! empty($toupload)) {
                $src  = $toupload['tmp_name'];
                $dest = 'img' . DS . 'slideshow' . DS . $toupload['name'];
                upload_file($src, $dest);
            }
            
            $this->setFlash('Stavka u izlogu je sačuvana.', 'ok');
        }
        
        $this->redirect('index');
    }
    
    public function remove($id) {
        if ($this->Slideshow->delete($id)) {
            $this->setFlash('Stavka je uspešno obirsana iz izloga.', 'ok');
        } else {
            $this->setFlash('Greška pri brisanju stavke.');
        }
        
        $this->redirect('index');
    }
    
    public function save_positions() {
        $positions = $this->data['positions'];
        
        $this->autoRender = false;
        if ($this->Slideshow->saveAll($positions)) {
            header('HTTP/1.0 GET 200');
        }else{
            header('HTTP/1.0 GET 404');
        }
    }
}